package com.tang.common.utils.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * @Author tang jun liang
 * @Date 2023/11/13 08:47
 */
public class BigDecimalConverter implements Converter<BigDecimal> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return BigDecimal.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public BigDecimal convertToJavaData(ReadConverterContext<?> context) throws Exception {
        String stringValue = context.getReadCellData().getStringValue();
        if (StringUtils.isNotBlank(stringValue)){
            return new BigDecimal(stringValue).setScale(2, RoundingMode.UP);
        }
        return BigDecimal.ZERO;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<BigDecimal> context) throws Exception {
        if (Objects.nonNull(context.getValue())){
            return new WriteCellData<>(new DecimalFormat("##,##0.00").format(context.getValue()));
        }
        return new WriteCellData<>(BigDecimal.ZERO);
    }
}
